package com.rongxue.service.Impl;


import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.ProductService;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


/**
 * Created by yangweijian on 2018/2/28.
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private SProductMapper sProductMapper;

    @Autowired
    private SUserMapper sUserMapper;

    @Autowired
    private SAddressMapper sAddressMapper;

    @Autowired
    private SOrderMapper sOrderMapper;

    @Autowired
    private SIntegralMapper sIntegralMapper;

    @Autowired
    private SUserInterestCouponMapper sUserInterestCouponMapper;

    @Autowired
    private SUserRedenvelopeMapper sUserRedenvelopeMapper;

    @Autowired
    private SAdvertisementMapper sAdvertisementMapper;

    @Override
    public ObjectResult index(XMLBean xmlBean) {
        Map<String, Object> map = new HashMap<>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        List<SProduct> list = sProductMapper.selectProductList(xmlBean.getCategory());
        Page<SProduct> page = new Page<>();
        page.setP(xmlBean.getP() == null ? 1 : xmlBean.getP());
        page.setPageSize(10);
        List<SProduct> content = page.getPageContent(list);
        for (SProduct sProduct : content) {
            sProduct.setImage(CashInAndOutServiceImpl.ADMIN_URL + sProduct.getImage());
            if (sProduct.getStatus() == 2) {
                sProduct.setSubtitle("即将上线");
            } else {
                sProduct.setSubtitle(sProduct.getIntegral() + "积分兑换");
            }
            sProduct.setStatus(null);
        }
        map.put("userId", userId);
        SUser user = sUserMapper.selectUserByMap(map);
        String mobile = CommonUtils.concealMobile(user.getMobile());

//        map.put("is_default",1);
//        List<SAddress> sAddressList = sAddressMapper.selectAddressByUserId(map);
        map.clear();
//        map.put("is_default",1);
//        if(sAddressList.size()==0){
//            map.put("is_default",0);
//        }
        //轮播图
        List<SAdvertisement> carousel = sAdvertisementMapper.selectAdvertisementList();
        for (SAdvertisement sAdvertisement : carousel) {
            sAdvertisement.setImage(CashInAndOutServiceImpl.ADMIN_URL + sAdvertisement.getImage());
        }
        //热门商品
        List<SProduct> hot = sProductMapper.selectProductIsHot();
        for (SProduct sProduct : hot) {
            sProduct.setImage(CashInAndOutServiceImpl.ADMIN_URL + sProduct.getImage());
        }

        map.put("mobile", mobile);
        map.put("integral", user.getIntegral());
        map.put("list", content);
        map.put("count", page.getPageTotal());
        map.put("carousel", carousel);
        map.put("hot", hot);
        return ObjectResult.build("1", "成功", map);
    }

    @Override
    public ObjectResult details(XMLBean xmlBean) {
        SProduct sProduct = sProductMapper.selectProductById(xmlBean.getId());
        List<Map<String, String>> list = new ArrayList<>();

        if (sProduct.getImage_list() != null && !"".equals(sProduct.getImage_list())) {
            //截取图片列表
            String[] split = sProduct.getImage_list().split("src");
            for (int i = 0; i < split.length - 1; i++) {
                Map<String, String> map = new HashMap<>();
                if (split[i + 1].contains("http") & split[i + 1].contains("jpg")) {
                    map.put("src", split[i + 1].substring(split[i + 1].lastIndexOf("http"), split[i + 1].lastIndexOf(".jpg") + 4));
                } else if (split[i + 1].contains("http") & split[i + 1].contains("png")) {
                    map.put("src", split[i + 1].substring(split[i + 1].lastIndexOf("http"), split[i + 1].lastIndexOf(".png") + 4));
                } else {
                    map.put("src", "");
                }
                list.add(map);
            }

        }
        sProduct.setList(list);
        sProduct.setImage(CashInAndOutServiceImpl.ADMIN_URL + sProduct.getImage());
        if (sProduct.getLong_image() != null && !"".equals(sProduct.getLong_image())) {
            sProduct.setLong_image(sProduct.getLong_image().substring(sProduct.getLong_image().lastIndexOf("http"), sProduct.getLong_image().lastIndexOf(".png") + 4));
        }

        return ObjectResult.build("1", "成功", sProduct);
    }

    @Override
    public ObjectResult exchange(XMLBean xmlBean) {
        Map<String, Object> map = new HashMap<>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SProduct product = sProductMapper.selectProductById(xmlBean.getId());
        map.put("userId", userId);
        SUser user = sUserMapper.selectUserByMap(map);
        if (user.getIntegral() < product.getIntegral()) {
            return ObjectResult.build("0", "积分不足无法兑换");
        }
        if (product.getSurplus()<1){
            return ObjectResult.build("0", "可兑换数为0");
        }

        if (product.getCategory() == 1) {
            SUserRedenvelope sUserRedenvelope = new SUserRedenvelope();
            sUserRedenvelope.setTitle("积分兑换红包");
            sUserRedenvelope.setContent("积分兑换红包");
            sUserRedenvelope.setUserId(Integer.parseInt(userId));
//            String s = product.getTitle().substring(0, product.getTitle().lastIndexOf("元"));
            sUserRedenvelope.setAmount(product.getValue());
            sUserRedenvelope.setCreateTime(new Date());
            sUserRedenvelope.setMinInvest(product.getMin_invest());
            sUserRedenvelope.setMinDue(product.getMin_due());
            sUserRedenvelope.setExpireTime(DateUtil.addDateDay(new Date(), product.getDay()));
            sUserRedenvelope.setStatus(0);
            sUserRedenvelope.setScope(0);
            sUserRedenvelope.setType(0);
            sUserRedenvelopeMapper.insertSelective(sUserRedenvelope);
        }
        if (product.getCategory() == 2) {
            SUserInterestCoupon interestCoupon = new SUserInterestCoupon();
            interestCoupon.setCouponId(0);
            interestCoupon.setTitle("积分兑换加息券");
            interestCoupon.setSubtitle("积分兑换加息券");
            interestCoupon.setUserId(Integer.parseInt(userId));
//            String s = product.getTitle().substring(0, product.getTitle().lastIndexOf("%"));
            interestCoupon.setInterestRate(product.getValue());
            interestCoupon.setMinDue(product.getMin_due());
            interestCoupon.setMinInvest(product.getMin_invest());
            interestCoupon.setExpireTime(DateUtil.addDateDay(new Date(), product.getDay()));
            interestCoupon.setStatus(0);
            interestCoupon.setScope(0);
            interestCoupon.setAddTime(new Date());
            sUserInterestCouponMapper.insertSelective(interestCoupon);
        }
        if (product.getCategory() == 3) {
            //添加订单
            SOrder order = new SOrder();

            SAddress sAddress = sAddressMapper.selectAddress(xmlBean.getAddress_id());

            //修改剩余件数
            if (product.getSurplus() > 0) {
                sProductMapper.updateSurplusById(xmlBean.getId());
            } else {
                return ObjectResult.build("0", "该商品可兑换数为0");
            }
            String orderId = CommonUtils.genOrderId();
            order.setOrder_id(orderId);
            order.setUser_id(Integer.parseInt(userId));
            order.setProduct_id(product.getId());
            order.setUser_name(sAddress.getUser_name());
            order.setProduct_code(product.getProduct_code());
            order.setProduct_title(product.getTitle());
            order.setUser_mobile(sAddress.getMobile());
            order.setNum(1);
            order.setIs_delete(0);
            order.setAddress(sAddress.getAddress());
            order.setStatus(1);
            sOrderMapper.insertOrder(order);
        }
        //修改积分
        map.put("integral", 0 - product.getIntegral());
        sUserMapper.updateIntegralAndRxgoldByMap(map);
        //添加积分记录;
        map.put("type", 4);
        sIntegralMapper.insertIntegralByMap(map);

        return ObjectResult.build("1", "兑换成功");
    }

    @Override
    public ObjectResult insertAddress(XMLBean xmlBean) {
        Map<String, Object> map = new HashMap<>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        map.put("userId", userId);
        if (xmlBean.getIs_default() == 1) {
            sAddressMapper.updateAddressAll(userId);
        }
        SUser user = sUserMapper.selectUserByMap(map);
        SAddress sAddress = new SAddress();
        sAddress.setUser_id(Integer.parseInt(userId));
        sAddress.setUser_name(xmlBean.getUser_name());
        sAddress.setMobile(xmlBean.getMobile());
        sAddress.setIs_default(xmlBean.getIs_default());
        sAddress.setAddtime(DateUtil.formatDateTime());
        sAddress.setAddress(xmlBean.getAddress());
        sAddressMapper.insertAddress(sAddress);

        return ObjectResult.build("1", "成功");
    }

    @Override
    public ObjectResult edit_address(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        if (xmlBean.getIs_default() == 1) {
            sAddressMapper.updateAddressAll(userId);
        }
        SAddress sAddress = new SAddress();
        sAddress.setId(xmlBean.getAddress_id());
        sAddress.setUser_id(Integer.parseInt(userId));
        sAddress.setMobile(xmlBean.getMobile());
        sAddress.setAddress(xmlBean.getAddress());
        sAddress.setIs_default(xmlBean.getIs_default());
        sAddress.setUser_name(xmlBean.getUser_name());
        sAddressMapper.updateAddress(sAddress);

        return ObjectResult.build("1", "成功");
    }

    @Override
    public ObjectResult del_address(XMLBean xmlBean) {
        Map<String, Object> map = new HashMap<>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        sAddressMapper.deleteAddress(xmlBean.getAddress_id());
        map.put("userId", userId);
        List<SAddress> list = sAddressMapper.selectAddressByUserId(map);
        //删除后仍有收货地址且无默认收货地址，设置新的默认地址
        if (list.size() > 0) {
            boolean flag = true;
            for (SAddress sAddress : list) {
                if (sAddress.getIs_default() == 1) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                SAddress sAddress = new SAddress();
                sAddress.setIs_default(1);
                sAddress.setId(list.get(0).getId());
                sAddressMapper.updateAddress(sAddress);
            }
        }
        return ObjectResult.build("1", "成功");
    }

}